import React, { useState, useEffect } from 'react';
import { 
  Container, Typography, Box, Grid, Card, CardMedia, 
  CardContent, Button, Dialog, DialogActions, 
  DialogContent, DialogContentText, DialogTitle,
  Pagination, CircularProgress, Alert
} from '@mui/material';
import { Delete as DeleteIcon } from '@mui/icons-material';
import { ResourceService, Resource, ResourceListResponse } from '../services/ResourceService';
import { useNavigate } from 'react-router-dom';

const MyResources: React.FC = () => {
  const [resources, setResources] = useState<Resource[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState<number>(1);
  const [totalPages, setTotalPages] = useState<number>(1);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState<boolean>(false);
  const [resourceToDelete, setResourceToDelete] = useState<Resource | null>(null);
  const [deleteSuccess, setDeleteSuccess] = useState<boolean>(false);
  const [deleteError, setDeleteError] = useState<string | null>(null);
  
  const pageSize = 9;
  const navigate = useNavigate();

  // 加载用户发布的资源列表
  const loadResources = async () => {
    setLoading(true);
    setError(null);
    setDeleteSuccess(false);
    setDeleteError(null);
    
    try {
      const response: ResourceListResponse = await ResourceService.getMyResources(page, pageSize);
      setResources(response.records);
      setTotalPages(Math.ceil(response.total / pageSize));
    } catch (err) {
      console.error('加载资源失败:', err);
      setError('加载资源失败，请稍后重试');
      setResources([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadResources();
  }, [page]);

  // 处理分页变化
  const handlePageChange = (event: React.ChangeEvent<unknown>, value: number) => {
    setPage(value);
  };

  // 打开删除确认对话框
  const handleOpenDeleteDialog = (resource: Resource) => {
    setResourceToDelete(resource);
    setDeleteDialogOpen(true);
  };

  // 关闭删除确认对话框
  const handleCloseDeleteDialog = () => {
    setDeleteDialogOpen(false);
    setResourceToDelete(null);
  };

  // 删除资源
  const handleDeleteResource = async () => {
    if (!resourceToDelete) return;
    
    setLoading(true);
    setDeleteError(null);
    
    try {
      await ResourceService.deleteResource(resourceToDelete.id);
      setDeleteSuccess(true);
      // 重新加载资源列表
      loadResources();
    } catch (err) {
      console.error('删除资源失败:', err);
      setDeleteError('删除资源失败，请稍后重试');
    } finally {
      setLoading(false);
      handleCloseDeleteDialog();
    }
  };

  // 跳转到资源详情页
  const handleViewResource = (resourceId: string) => {
    navigate(`/resources/${resourceId}`);
  };

  return (
    <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
      <Typography variant="h4" component="h1" gutterBottom>
        我的资源管理
      </Typography>
      
      {deleteSuccess && (
        <Alert severity="success" sx={{ mb: 2 }}>
          资源删除成功！
        </Alert>
      )}
      
      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}
      
      {deleteError && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {deleteError}
        </Alert>
      )}
      
      {loading ? (
        <Box display="flex" justifyContent="center" my={4}>
          <CircularProgress />
        </Box>
      ) : resources.length === 0 ? (
        <Box my={4}>
          <Typography variant="h6" align="center">
            您还没有发布任何资源
          </Typography>
        </Box>
      ) : (
        <>
          <Grid container spacing={3}>
            {resources.map((resource) => (
              <Grid item xs={12} sm={6} md={4} key={resource.id}>
                <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
                  <CardMedia
                    component="img"
                    height="250"
                    image={resource.coverUrl || resource.coverImageUrl || '/placeholder-image.jpg'}
                    alt={resource.title}
                    sx={{ objectFit: 'cover', cursor: 'pointer' }}
                    onClick={() => handleViewResource(resource.id)}
                  />
                  <CardContent sx={{ flexGrow: 1 }}>
                    <Typography gutterBottom variant="h6" component="div" noWrap>
                      {resource.title}
                    </Typography>
                    <Typography variant="body2" color="text.secondary" sx={{ 
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      display: '-webkit-box',
                      WebkitLineClamp: 2,
                      WebkitBoxOrient: 'vertical'
                    }}>
                      {resource.description}
                    </Typography>
                    <Box sx={{ mt: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <Typography variant="body2" color="text.secondary">
                        状态: {resource.reviewStatus === 'WAIT' ? '审核中' : 
                              resource.reviewStatus === 'PASS' ? '已通过' : 
                              resource.reviewStatus === 'REFUSE' ? '已拒绝' : '未知'}
                      </Typography>
                      <Button
                        variant="outlined"
                        color="error"
                        startIcon={<DeleteIcon />}
                        size="small"
                        onClick={() => handleOpenDeleteDialog(resource)}
                      >
                        删除
                      </Button>
                    </Box>
                  </CardContent>
                </Card>
              </Grid>
            ))}
          </Grid>
          
          <Box display="flex" justifyContent="center" mt={4}>
            <Pagination 
              count={totalPages} 
              page={page} 
              onChange={handlePageChange} 
              color="primary" 
            />
          </Box>
        </>
      )}
      
      {/* 删除确认对话框 */}
      <Dialog
        open={deleteDialogOpen}
        onClose={handleCloseDeleteDialog}
      >
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <DialogContentText>
            您确定要删除资源 "{resourceToDelete?.title}" 吗？此操作不可撤销。
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDeleteDialog} color="primary">
            取消
          </Button>
          <Button onClick={handleDeleteResource} color="error" autoFocus>
            删除
          </Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
};

export default MyResources;